package com.quanyan.ic.vendingMachine.protocol.server.handler;

import com.quanyan.ic.vendingMachine.http.service.VmUpgradeService;
import com.quanyan.ic.vendingMachine.protocol.Cmd;
import com.quanyan.ic.vendingMachine.protocol.Code;
import com.quanyan.ic.vendingMachine.protocol.codec.protobuf.VmMessageProto;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by zhuo.shi on 2017/8/4.
 * 更新、升级应答消息，打印
 */
@Component("UpdateCmdRespHandler")
@ChannelHandler.Sharable
public class UpdateCmdRespHandler extends ChannelInboundHandlerAdapter {

    public static final Logger logger = LoggerFactory.getLogger(UpdateCmdRespHandler.class);

    @Autowired
    private VmUpgradeService service;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        VmMessageProto.VmMessage vmMessage = (VmMessageProto.VmMessage) msg;
        int cmd = vmMessage.getCmd();
        if (cmd == Cmd.UPDATE_GOODSLIST_RESP.getValue() || cmd == Cmd.UPDATE_POSTER_RESP.getValue()) {
            logger.info("received cmd update: msg=\n{}", vmMessage);
        } else if (cmd == Cmd.UPGRADE_RESP.getValue()) {
            logger.info("received cmd upgrade: msg=\n{}", vmMessage);
            //1.下发成功。2下载成功 3.下载失败
            int status ;
           if (vmMessage.getRespCode() == Code.RC_200.getValue())
               status= 2 ;
           else
               status=3;
            service.updateUpgradeRecord(vmMessage.getVmNumber(),vmMessage.getUpgradeFileType(),status);
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
